import javax.servlet.ServletContext;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Base64;
import java.sql.*;
class DatabaseConnect {
    String sqlurl;
    String sqlname;
    String sqlpasswd;

    public DatabaseConnect(ServletContext sc)
    {
       sqlurl  = sc.getInitParameter("db.url");
       sqlname  = sc.getInitParameter("db.user");
       sqlpasswd  = sc.getInitParameter("db.password");
    }

    public void updatesql(UserBean ub)
    {
	try (Connection conn = DriverManager.getConnection(sqlurl, sqlname, sqlpasswd)) {
	    PreparedStatement stat = conn.prepareStatement(" insert into `user` (`username`,`passwd`,`familyname`,`name`,`email`) values (?,?,?,?,?)");
	    stat.setString(1,ub.getUsername());
	    stat.setString(2,ub.getPasswd());
	    stat.setString(3,ub.getFamilyname());
	    stat.setString(4,ub.getName());
	    stat.setString(5,ub.getEmail());

	    stat.execute();
	} catch (SQLException e) {
	    e.printStackTrace();
	}
    }

	public void updateportrait(String username, InputStream portrait){
	    try (Connection conn = DriverManager.getConnection(sqlurl, sqlname, sqlpasswd)) {
	    PreparedStatement stat = conn.prepareStatement(" insert into `image` (`username`,`portrait`) values (?,?)");
	    stat.setString(1,username);
	    stat.setBlob(2,portrait);
	    stat.execute();
	    System.out.println("updateportrait complete");

	    }catch (SQLException e){
		e.printStackTrace();
	    }

	}
	public String getimage(String username)
	{
	    String base64Image=null;
	    try (Connection conn = DriverManager.getConnection(sqlurl, sqlname, sqlpasswd)) {
		PreparedStatement stat = conn.prepareStatement("select * from image where username = ?");
		stat.setString(1,username);
		ResultSet rs=stat.executeQuery();

		if(!rs.next())
		{
		    stat.setString(1,"admin");
		    rs=stat.executeQuery();
		    rs.next();
		}

		Blob blob =rs.getBlob("portrait");
		InputStream inputStream = blob.getBinaryStream();
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int bytesRead = -1;

		while ((bytesRead = inputStream.read(buffer)) != -1) {
		    outputStream.write(buffer, 0, bytesRead);                  
		}

		byte[] imageBytes = outputStream.toByteArray();
		base64Image = Base64.getEncoder().encodeToString(imageBytes);

		inputStream.close();
		outputStream.close();

	    }catch (SQLException | IOException e){
		e.printStackTrace();

	    }
	    return base64Image;

	}
    }

